package de.se.ludoapp.activity.task;

import android.content.Intent;
import android.os.AsyncTask;
import de.se.ludoapp.LudoApplication;
import de.se.ludoapp.activity.GameActivity;
import de.se.ludoapp.activity.NewGameActivity;
import de.se.ludoapp.gaming.Game;
import de.se.ludoapp.response.GameFieldResponse;

/**
 * Task to start a new game on the server.
 * 
 * @author Marlen Rotert
 * 
 */
public class StartGameTask extends AsyncTask<String, Integer, String> {

	private LudoApplication ludoApp;
	private NewGameActivity context;

	public StartGameTask(LudoApplication ludoApp, NewGameActivity context) {
		super();
		this.ludoApp = ludoApp;
		this.context = context;
	}

	/**
	 * start new Game on Server.<br>
	 * This method is executed in a concurrent thread (asynchronous). Therefore
	 * you mustn't accessed on view elements!
	 */
	@Override
	protected String doInBackground(String... params) {
		/* Execute Start Game */
		GameFieldResponse gameFieldResponse = ludoApp.getLudoStub().startGame(
				ludoApp.getlogedinUser().getSessionId(),
				ludoApp.getCurrentGame().getGameId());
		Game game = ludoApp.getCurrentGame();
		game.setGameField(gameFieldResponse.getGameField());
		game.setUpNext(gameFieldResponse.getUpNext());
		if (gameFieldResponse.hasArtificialOpponentPlayer()) {
			game.setNameRedPlayer("Computer");
		}
		return gameFieldResponse.getMsg();
	}

	/**
	 * load playground <br>
	 * This method is invoked when the OpenGameTask is executed. You are only
	 * allowed here to access on view Elements (TextView and Buttons)!
	 */
	@Override
	protected void onPostExecute(String result) {
		Intent intentGame = new Intent(context, GameActivity.class);
		context.startActivity(intentGame);
		context.finish();
	}
}
